package com.zhuhjay.boot.jobs;

import com.zhuhjay.constant.RedisConstant;
import com.zhuhjay.utils.QiniuUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Set;

/**
 * 自定义定时任务, 来进行计算及删除redis中存在七牛云图片的垃圾资源
 * @author ZhuHJay
 * @date 2022/4/2 22:07
 */
public class ClearImageJob extends QuartzJobBean {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        // 通过redis中两个集合的差值来获取无效的图片资源
        Set<String> difference = redisTemplate.opsForSet()
                .difference(
                        RedisConstant.SETMEAL_PIC_RESOURCES,
                        RedisConstant.SETMEAL_PIC_DB_RESOURCES
                );
        if( difference != null ){
            difference.forEach(imageName -> {
                // 进行垃圾文件的删除
                QiniuUtils.deleteFileFromQiniu(imageName);
                // 从redis中删除该图片的记录
                redisTemplate.opsForSet()
                        .remove(RedisConstant.SETMEAL_PIC_RESOURCES, imageName);
            });
        }
    }

}
